import Vue from 'vue';
import Vuex from 'vuex';
import router from '../router';
import { getUserRolePowerForApp } from '@/api/userRole';
import { getMessageStatus } from '@/api/common.js';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    tabbarActive: 0,
    apps: [],
    buttons: [],
    noDetailPermissionText: '暂无查看详情权限，请联系管理员开通',
    isRefreshAuth: false,
    messageNum: {
      unread: 0,
      alarm: 0
    }
  },
  mutations: {
    // 去登录页
    toLogin() {
      localStorage.setItem('token', '');
      router.push('/');
    },
    // 重置isRefreshAuth
    resetIsRefreshAuth(state) {
      state.isRefreshAuth = false;
    },
    // 重置tabbar下标
    resetTabbarActive(state, index) {
      state.tabbarActive = index;
    },
    // 设置未读消息条数
    setUnreadMsgNum(state, num) {
      state.messageNum.unread = num;
    },
    // 设置报警消息条数
    setAlarmMsgNum(state, num) {
      state.messageNum.alarm = num;
    }
  },
  actions: {
    async generateAhthButtons({ commit, state }) {
      // 获取用户权限
      let authorityData = await getUserRolePowerForApp();
      if (authorityData.data && authorityData.data.length) {
        let apps = [];
        let btns = [];
        authorityData.data.map(item => {
          if (item.is_app) {
            apps.push(item);
          } else {
            btns.push(item.auth_name);
          }
        });
        let appSort = ['iot_project', 'iot_maintenance', 'iot_device'];
        let newApps = [];
        appSort.map(item => {
          apps.map(subItem => {
            if (subItem.request_name === item) {
              newApps.push(subItem);
            }
          });
        });
        state.apps = newApps;
        state.buttons = btns;
        state.isRefreshAuth = true;
      }
    },
    // 获取消息类型及条数
    getMessageStatusAndNum({ commit, state }) {
      getMessageStatus().then(res => {
        let { callPolice, unread } = res.data;
        callPolice = callPolice > 99 ? '99+' : callPolice;
        if (unread === 0 && callPolice === 0) {
          callPolice = '';
        }
        commit('setAlarmMsgNum', callPolice);
        commit('setUnreadMsgNum', unread);
      });
    }
  },
  modules: {}
});
